package com.java46.front.user.dao;

import com.java46.admin.base.exception.BusinessException;
import com.java46.admin.base.util.HibernateUtils;
import com.java46.admin.user.entity.UsersEntity;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import java.util.List;

public class UserDao {
    /**
     * 添加用户
     * @param openId
     * @return
     */
    public void addUser(String openId){
        Session session = HibernateUtils.getSession();
        try{
            Transaction transaction = session.beginTransaction();
            UsersEntity usersEntity = new UsersEntity();
            usersEntity.setOpenId(openId);
            try{
                session.save(usersEntity);
                transaction.commit();
            }catch (BusinessException be){
                throw new BusinessException("天哪，数据添加失败了");
            }
        }catch(RuntimeException re){
            throw re;
        }finally {
            session.close();
        }
    }
    /**
     * 查询是否有该用户
     */
    public UsersEntity queryUser(String openId) {

        // TODO Auto-generated method stub
        UsersEntity userEntity =null;
        Session session = HibernateUtils.getSession();
        try{
            Query query = session.createQuery("from com.java46.admin.user.entity.UsersEntity as a where a.openId = ?1");
            query.setParameter(1,openId);
            List list = query.list();
            if(list.size()!=0){
                userEntity = (UsersEntity)query.list().get(0);
            }
        }catch(RuntimeException re){
            throw re;
        }finally {
            session.close();
        }
        return userEntity;
    }

}
